package cool.taomu.toolkit.service.kademlia.provider

import com.google.gson.Gson
import com.google.inject.Inject
import com.google.inject.Provider
import com.google.inject.name.Named
import cool.taomu.toolkit.rpc.thrift.entity.ThriftConfig
import cool.taomu.toolkit.service.kademlia.entity.Constant
import cool.taomu.toolkit.service.kademlia.entity.KPeerNode
import cool.taomu.toolkit.service.kademlia.utils.KademliaUtils
import cool.taomu.toolkit.service.kademlia.utils.TorrentUtils
import java.io.File
import java.util.List
import java.util.WeakHashMap
import org.apache.commons.io.FileUtils
import org.slf4j.LoggerFactory

class KPeerNodeProvider implements Provider<KPeerNode> {
    val static LOG = LoggerFactory.getLogger(KPeerNodeProvider)

    @Inject
    List<ThriftConfig> config;

    @Inject
    @Named("taomu.kademlia.name")
    String name;

    override get() {
        if (name.equalsIgnoreCase("localhost")) {
            var localNode = new KPeerNode("localhost", 18080);
            localNode.id = KademliaUtils.createNodeId();
            LOG.info("生成的本地节点信息:{}", localNode)
            return localNode
        }
        var server = config
        val cache = new WeakHashMap<String, ThriftConfig>();
        server.forEach [ c |
            cache.put(c.name, c)
        ]
        var info = cache.get(name);
        val localNode = new KPeerNode(info.host, info.port);
        localNode.id = KademliaUtils.createNodeId();

        LOG.info("生成的本地节点信息:{}", localNode)
        var torrent = new File(Constant.TORRENT_DOWNLOAD_PATH)
        if (!torrent.exists) {
            torrent.mkdirs
        }
        // 创建配置文件
        var nodeInfoFilePath = #[localNode.host, localNode.port, "local", "json"].join(".")
        var nodeInfoFile = new File(Constant.TORRENT_DOWNLOAD_PATH + File.separator + nodeInfoFilePath);
        var long pieceLength = 262144L;
        if (!nodeInfoFile.exists) {
            LOG.info("配置文件不存在，开始创建文件")
            FileUtils.write(nodeInfoFile, new Gson().toJson(localNode), "UTF-8");
            TorrentUtils.create(nodeInfoFile, pieceLength);
        } else {
            LOG.info("配置文件存在，开始加载")
            var jsonStr = FileUtils.readFileToString(nodeInfoFile, "UTF-8")
            var localNode2 = new Gson().fromJson(jsonStr, KPeerNode)
            return localNode2
        }
        return localNode
    }

}
